package pl.alipiec.stockview.client;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import pl.alipiec.stockview.StockViewException;
import pl.alipiec.stockview.StockViewHelper;

/**
 * Prosty klient dla celow testowych
 * 
 * @author Aleksandra Lipiec
 * 
 */
public class SimpleClient {

	private Connection connection = null;
	private InitialContext initialContext = null;
	private Session session;
	private MessageConsumer messageConsumer;

	public void connect() throws StockViewException {
		try {
			initialContext = StockViewHelper.getContext();

			Topic queue = (Topic) initialContext.lookup("/topic/indexMedia");

			ConnectionFactory cf = (ConnectionFactory) initialContext
					.lookup("/client/ConnectionFactory");

			connection = cf.createConnection();

			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			messageConsumer = session.createConsumer(queue);

			connection.start();

		} catch (Exception e) {
			System.out.println("No connection");
			e.fillInStackTrace();
			throw new StockViewException(e);
		}
	}

	public void receiveMessage() throws StockViewException {
		try {
			TextMessage messageReceived = (TextMessage) messageConsumer
					.receive(35000);
			System.out
					.println("Received message: " + messageReceived.getText());
		} catch (Exception e) {
			System.out.println("Error while waiting for a message");
			e.fillInStackTrace();
			throw new StockViewException(e);
		}
	}

	public void closeConnection() {

		if (initialContext != null) {
			try {
				initialContext.close();
			} catch (NamingException e) {
				// TODO: log
				e.printStackTrace();
			}
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (JMSException e) {
				// TODO: log
				e.printStackTrace();
			}
		}

	}

	public static void main(String[] args) throws Exception {
		SimpleClient client = new SimpleClient();
		try {
			client.connect();
			while (true) {
				client.receiveMessage();
			}
		} finally {
			client.closeConnection();
		}
	}

}
